import React, { useState, useEffect } from 'react';
import { Card, Input, Button, message, Typography, Space, Avatar, Spin } from 'antd';
import { UserOutlined, LoginOutlined, TeamOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { authService } from '../lib/authService';

const { Title, Text } = Typography;

interface Manager {
  id: string;
  name: string;
  specialty: string;
  is_online: boolean;
  connection_count: number;
  status: string;
}

export default function ManagerLoginPage() {
  const [managerName, setManagerName] = useState('');
  const [password, setPassword] = useState('');
  const [isLogging, setIsLogging] = useState(false);
  const [managers, setManagers] = useState<Manager[]>([]);

  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    if (authService.isAuthenticated()) {
      message.info('您已登录，将自动跳转到工作台。');
      navigate('/dashboard', { replace: true });
    }
  }, [navigate]);

  // 获取当前在线经理列表
  const fetchAvailableManagers = async () => {
    try {
      const response = await fetch('/api/managers/available');
      const result = await response.json();
      if (result.success) {
        setManagers(result.data);
      } else {
        console.error('获取经理列表失败');
      }
    } catch (error) {
      console.error('Error fetching managers:', error);
    }
  };

  useEffect(() => {
    fetchAvailableManagers();
    // 每30秒刷新一次在线经理列表
    const interval = setInterval(fetchAvailableManagers, 30000);
    return () => clearInterval(interval);
  }, []);

  // 检查名字是否已被使用
  const isNameTaken = (name: string): boolean => {
    return managers.some(manager => 
      manager.name.toLowerCase() === name.toLowerCase() && manager.is_online
    );
  };

  // 登录处理
  const handleLogin = async () => {
    if (!managerName.trim()) {
      message.error('请输入理财师姓名');
      return;
    }

    if (!password.trim()) {
      message.error('请输入密码');
      return;
    }

    const trimmedName = managerName.trim();

    // 检查重名
    if (isNameTaken(trimmedName)) {
      message.error('该理财师姓名已被使用，请选择其他名字');
      return;
    }

    setIsLogging(true);

    try {
      // 使用新的authService认证方法
      const result = await authService.authenticate({
        username: trimmedName,
        password: password
      });

      if (result.success && result.data) {
        // 通过authService统一管理WebSocket连接
        authService.login(result.data);
        
        message.success(`欢迎，${result.data.name}！登录成功`);
        setIsLogging(false);
        
        const from = location.state?.from?.pathname;
        if (from === '/client-test') {
          navigate('/client-test');
        } else {
          navigate('/dashboard');
        }
      } else {
        message.error(result.message || '登录失败');
        setIsLogging(false);
      }

    } catch (error) {
      console.error('Login error:', error);
      setIsLogging(false);
      message.error('登录失败，请稍后重试');
    }
  };

  // 处理回车键登录
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleLogin();
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
      <div className="flex items-center justify-center w-full">
        <Card 
          className="w-full max-w-md shadow-2xl border-0"
          styles={{ body: { padding: '48px' } }}
        >
            <div className="text-center mb-8">
              <Avatar size={80} icon={<TeamOutlined />} className="bg-blue-500 mb-4" />
              <Title level={2} className="!mb-2 text-gray-800">理财师登录</Title>
              <Text type="secondary">输入您的姓名开始工作</Text>
            </div>

            <Space direction="vertical" size="large" className="w-full">
              <div>
                <Text strong className="block mb-2 text-gray-700">理财师姓名</Text>
                <Input
                  value={managerName}
                  onChange={(e) => setManagerName(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="请输入您的姓名"
                  size="large"
                  prefix={<UserOutlined className="text-gray-400" />}
                  disabled={isLogging}
                  className="rounded-lg"
                />
                {managerName.trim() && isNameTaken(managerName.trim()) && (
                  <Text type="danger" className="text-sm mt-1 block">
                    该姓名已被使用，请选择其他名字
                  </Text>
                )}
              </div>
              <div>
                <Text strong className="block mb-2 text-gray-700">密码</Text>
                <Input.Password
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="请输入密码"
                  size="large"
                  prefix={<LockOutlined className="text-gray-400" />}
                  disabled={isLogging}
                  className="rounded-lg"
                />
              </div>
              <Button
                type="primary"
                size="large"
                icon={isLogging ? <Spin size="small" /> : <LoginOutlined />}
                onClick={handleLogin}
                loading={isLogging}
                disabled={!managerName.trim() || isNameTaken(managerName.trim())}
                className="w-full h-12 rounded-lg font-medium"
              >
                {isLogging ? '正在登录...' : '登录'}
              </Button>
            </Space>

          </Card>
        </div>
    </div>
  );
} 